/* 用户信息列表页面 */
<template>
  <!-- 主布局 -->
  <div class="container">
    <!-- 卡片式布局 -->
    <el-card>
      <el-row :gutter="25">
        <!--设置间隙  -->
        <!-- 搜索区域 -->
        <el-col :span="10"
          ><!-- 列宽 -->
          <el-input
            placeholder="请输入搜索内容"
            v-model="fromData.name"
            clearable
            @cleaer="searchUserList"
          >
            <!-- 搜索功能按钮，用语法糖绑定查询用户的方法 -->
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchUserList"
            ></el-button>
          </el-input>
        </el-col>

        <el-col :span="4">
          <!-- 添加用户按钮 -->
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表 ,border为边框，stripe隔行变色 -->
      <el-table
        style="
          font-size: 14px;
          box-shadow: 10px 10px 5px rgba(99, 99, 153, 0.2);
        "
        :data="userList"
        border
        stripe
        :header-cell-style="{ background: '#f8f8f9', color: '#515a6e' }"
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column
          label="用户名"
          prop="username"
          align="center"
        ></el-table-column>
        <el-table-column
          label="邮箱"
          prop="email"
          align="center"
        ></el-table-column>
        <el-table-column
          label="密码"
          prop="password"
          align="center"
        ></el-table-column>
        <el-table-column
          label="角色"
          prop="role"
          align="center"
        ></el-table-column>
        <el-table-column label="登录状态" prop="state" align="center">
          <!-- 作用域操作 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.state"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete(scope.$index, scope.row)"
            ></el-button>
            <!-- 权限 -->
            <el-tooltip
              effect="dark"
              content="分配权限"
              placement="top-start"
              :enterable="false"
              ><!--文字提示 enterable 隐藏-->
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- 索引列 -->
      </el-table>
      <div
        class="block"
        style="
          text-align: center;
          margin-top: 15px;
          margin-left: 10px;
          padding: 10px 10px;
        "
      >
        <div>
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="fromData.pageIndex"
            :page-sizes="pageInfo.pageSizes"
            :page-size="fromData.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageInfo.total"
          >
            <!-- @size-change：每页显示条数个数点击事件，当切换时动态的切换每页显示的条数
               @current-change：当前页数点击事件
               current-page:当前页码，默认为第一页
               page-sizes：在页面可选择的页码数[1,10,20,50] 
               page-size：每页显示的条数，可以动态的修改
               total：显示的是从后端获得数据的总数  -->
          </el-pagination>
        </div>
      </div>
    </el-card>
    <!-- 新增用户区域 -->
    <el-dialog
      center
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="AddFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
      </el-form>

      <!-- 内容底部区域，两个按钮区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="doAddUser">确定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框区域 -->
    <el-dialog
      center
      title="修改用户信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password" disabled></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
      </el-form>

      <!-- 内容底部区域，两个按钮区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="doModifyUser">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  list,
  delUser,
  recycle,
  updateUser,
  addUser,
} from "../../api/user/index";
export default {
  //created()方法指的是在页面开启的同时就调用里面的方法。
  created() {
    this.queryUserList(); //获取当前用户列表
    const loading = this.$loading({
      lock: true,
      text: "数据加载中......",
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.7)",
    });
    setTimeout(() => {
      loading.close();
    }, 1000); /* 设置时间为1秒 */
  },
  //数据定义
  data() {
    return {
      userList: [], //用户列表
      username: "", //用户名
      total: 0, //总记录数为0
      //查询信息封装实体
      fromData: {
        name: "",
        pageIndex: 1, //当前页码，为第一页
        pageSize: 5, //默认每页最大数为5，可以动态的切换每页最大数
      },
      pageInfo: {
        total: 0, //总数，初始值为0
        pageSizes: [1, 5, 10, 20], //定义每次显示最大的条数
      },
      addDialogVisible: false, //添加用户表单对话框状态，默认为true
      editDialogVisible: false, //修改表单对话框状态，默认为true
      //添加用户的信息
      addForm: {
        id: 0,
        username: "",
        password: "",
        email: "",
      },
      //修改用户的信息
      editForm: {
        username: "",
        password: "",
        email: "",
        id: 0,
      },
      //表单验证规则
      AddFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 5 到 8 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 0,
            max: 10,
            message: "长度在 5 到 10 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { min: 0, max: 15, message: "请输入正确的邮箱", trigger: "blur" },
        ],
      },
      //表单验证规则
      editFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 5 到 8 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "长度在 5 到 10 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { min: 2, max: 15, message: "请输入正确的邮箱", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    /* 查询用户方法 */
    queryUserList() {
      var $that = this;
      list(this.fromData).then((res) => {
        if (res.code == 200 && res.success == "success") {
          $that.userList = res.data.list;
          $that.pageInfo.total = res.data.total;
        }
      });
    },

    //查询用户的方法，通过模糊查询查看用户是否存在，不过存在一些细节问题
    searchUserList() {
      let result = "";
      this.queryUserList(); //调用list方法
      result = this.fromData.name; //获得当前输入框的数据
      if (result.length > 0) {
        this.$message({
          message: "查询成功，结果如下",
          type: "success",
        });
      } else if (result.length == 0) {
        this.$message({
          message: "当前输入的信息为空",
          type: "info",
        });
      } else {
        this.$message.error("查询的结果不存在");
      }
    },

    /* 更改用户状态方法 */
    async userStateChanged(userInfo) {
      var formData = new FormData();
      formData.append("id", userInfo.id);
      formData.append("state", userInfo.state);
      const { data: res } = await this.$http.put(
        "sys/user/userState",
        formData
      ); //调用后台userState的接口，将信息存放在formData中
      const confirmResult = await this.$confirm(
        "此操作更改用户状态将无法登录,是否继续",
        "提示",
        {
          confirmButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning",
        }
      ).catch((err) => err);
      if (res != "success" && confirmResult != "confirm") {
        userInfo.id = !userInfo.id;
        return this.$message.error("修改用户状态失败");
      }
      this.$message.success("修改用户状态成功");
    },

    //监听添加用户的操作，点击取消然后退出对话框
    addDialogClosed() {
      this.$refs.addFormRef.resetFields(); //重置对话框
    },

    //增加图书,方法已实现
    doAddUser() {
      var $that = this;
      addUser(this.addForm).then((res) => {
        if (res.code == 200 && res.success == "success") {
          this.queryUserList();
          this.$message({
            message: "增加用户: " + $that.addForm.username + " 成功",
            type: "success",
          });
          $that.addDialogVisible = false;
          $that.addForm.username = "";
        }
      });
    },

    //删除用户方法,在删除用户的同时,将数据存放在回收站中,后期可以进行恢复
    handleDelete(id, row) {
      //确认信息提示框
      this.$confirm(
        "此操作将删除 " + row.username + " （可在回收站中找回）, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          //为了用户信息备份功能 把传入单个参数变成传入多个参数
          var params = {
            id: row.id, //用户id
            userId: row.userId, //用户权限id
            username: row.username, //用户用户名
            password: row.password, //用户密码
            email: row.email, //用户邮箱
            role: row.role, //用户角色
            state: row.state, //用户登录状态
            createTime: row.createTime, //用户创建时间
            modifyTime: row.modifyTime,
          };
          //先进行回收,其次进行删除
          recycle(params).then(); //将数据插入recycle回收表中
          delUser(params).then((res) => {
            //清空user表中的数据
            if (res.code == 200 && res.success == "success" && res.data >= 1) {
              this.$message({
                type: "success",
                message: "删除" + row.username + "成功!",
              });
              this.queryUserList(); //删除后重新查询即刷新数据
            } else {
              this.$message({
                type: "success",
                message: "删除" + row.username + "失败!",
              });
            }
          });
        })
        .catch(() => {
          //点击取消按钮
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //关闭对话框方法
    editDialogClosed() {
      this.$refs.editFormRef.resetFields(); //重置对框框区域信息
    },

    //获得对话框信息，具体到当前所选择的用户
    handleEdit(index, row) {
      this.editDialogVisible = true; //显示对话框
      this.editForm.id = row.id; //获得当前用户id
      this.editForm.username = row.username; //获得当前用户名
      this.editForm.password = row.password; //获得当前密码
      this.editForm.email = row.email; //获得当前邮箱信息
    },

    //修改用户信息方法,bug修复 -06-07
    doModifyUser() {
      var $that = this;
      updateUser(this.editForm).then((res) => {
        if (res.code == 200 && res.success == "success") {
          this.queryUserList();
          console.log(this.editForm.username);
          console.log(this.editForm.password);
          console.log(this.editForm.email);
          this.$message({
            message: "修改 " + $that.editForm.username + " 成功",
            type: "success",
          });
          //将数据进行初始化
          $that.editDialogVisible = false;
          $that.editForm.username = "";
          $that.editForm.password = "";
          $that.editForm.email = "";
          $that.editForm.id = 0;
        } else {
          this.$message({
            message: "修改 " + $that.editForm.username + " 失败",
            type: "danger",
          });
        }
      });
    },

    //每页显示的条目个数的1改变
    handleSizeChange(val) {
      this.fromData.pageSize = val; //重新对每页显示条数进行更改
      this.queryUserList(); //重新获得列表的值
    },
    //当前页数的改变
    handleCurrentChange(val) {
      this.fromData.pageIndex = val; //对当前页数进行更改
      this.queryUserList(); //重新获得员工列表的值
    },
  },
  // //最大数的改变， newSize：新的页码
  // handleSizeChange(newSize) {
  //   this.queryInfo.pageSize = newSize;
  //   this.queryUserList(); //获取当前用户列表
  // },

  // //页面变化pageNum的触发功能，newPage：新的分页数
  // handleCurrentChange(newPage) {
  //   this.queryInfo.pageNum = newPage;
  //   this.queryUserList(); //获取当前用户列表
  // },
  //添加用户的方法
  /// addUser() {
  //   this.$refs.addFormRef.validate(async (valid) => {
  //     if (!valid) return;
  //     const { data: res } = await this.$http.post(
  //       "sys/user/addUser",
  //       this.addForm
  //     ); //通过post请求调用后台addUser的api接口，并把参数存放在addForm里面
  //     if (res != "success") {
  //       //如何失败，则返回错误信息
  //       return this.$message.error("操作失败");
  //     }
  //     this.$message.success("操作成功");
  //     this.addDialogVisible = false; //将对话框消失
  //     this.queryUserList(); //重新调用获取用户列表的方法
  //   });
  // },

  //删除用户的方法，根据id主键删除 4.1
  // async deleteUser(id, row) {
  //   const confirmResult = await this.$confirm(
  //     "此操作将删除用户,是否继续",
  //     "提示",
  //     {
  //       confirmButtonText: "确定",
  //       confirmButtonText: "取消",
  //       type: "warning",
  //     }
  //   ).catch((err) => err);
  //   if (confirmResult != "confirm") {
  //     //若点击取消删除的按钮，则显示message的提示信息
  //     return this.$message.info("已取消删除");
  //   }
  //   const { data: res } = await this.$http.delete(
  //     "sys/user/deleteUser?id=" + id
  //   );
  //   if (res != "success") {
  //     return this.$message.error("删除" + this.row.username + "失败");
  //   }
  //   this.$message.success("删除" + this.row.username + "成功");
  //   this.queryUserList(); //重新调用获取所有用户的方法，重现显示在视图页面
  // },
  // //修改用户信息的方法
  // editUser() {
  //   this.$refs.editFormRef.validate(async (valid) => {
  //     if (!valid) return;
  //     const { data: res } = await this.$http.put(
  //       "sys/user/editUser",
  //       this.editForm
  //     );
  //     if (res != "success") return this.$message.error("修改失败！！！");
  //     this.$message.success("修改用户信息成功");
  //     this.editDialogVisible = false;
  //     this.queryUserList(); //重新获得用户列表信息
  //   });
  // },
  // //显示对话框，并且获得用户信息，这个方法后期需要修改
  // async showEditDialog(id) {
  //   const { data: res } = await this.$http.get(
  //     "sys/user/getUpdateUser?id=" + id
  //   );
  //   this.editForm = res; //查询用户信息存放在editform中
  //   this.editDialogVisible = true; //开启编辑对话框
  // },
};
</script>

<style Lang="less" scoped>
</style>